#include <iostream>
#include <memory>
using namespace std;

class A;
class B;

class A {
public:
    shared_ptr<B> bptr;
    ~A() {
        cout << "A is deleted" << endl;
    }
};

class B {
public:
    shared_ptr<A> aptr;
    ~B() {
        cout << "B is deleted" << endl;
    }
};

int main() {
    shared_ptr<A> pa;
    {
        shared_ptr<A> ap(new A);
        shared_ptr<B> bp(new B);
        ap->bptr = bp;
        bp->aptr = ap;
        pa = ap;

        // 手动释放成员变量才行
        ap->bptr.reset();
    }
    cout << "main leave. pa.use_count() = " << pa.use_count() << endl; // 循环引用导致ap bp退出了作用域都没有析构
    return 0;
}
/*
B is deleted
main leave. pa.use_count() = 1
A is deleted
*/